<?php

namespace App\Http\Controllers\Api\Admin;

use App\Classify;
use App\Enterprise;
use App\EnterpriseAdmin;
use App\Files;
use App\Http\Services\AdminManager;
use App\Http\Services\FileManager;
use App\Http\Services\MerchantManager;
use App\Images;
use App\Jobs\import;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantMedicineApply;
use App\MerchantMedicineImg;
use App\MerchantMedicineSku;
use App\MerchantMedicineSkuValue;
use App\MerchantMedicineXClassify;
use App\Sku;
use App\SkuValue;
use App\SystemMedicine;
use App\SystemMedicineImg;
use App\SystemMedicineSku;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;
use Maatwebsite\Excel\Facades\Excel;

class GoodsController extends Controller
{
    /**
     * 商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page         = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit        = !is_null($request->get('limit')) ? $request->get('limit') : 16;
        $status       = $request->get('status') ?? '';
        $classifyId   = $request->get('classify_id') ?? 0;
        $from         = $request->get('from') ?? '';
        $keyword      = $request->get('keyword') ?? '';

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var SystemMedicine $goods */
        $goodsList = SystemMedicine::whereNull('deleted_at');

        if($keyword != ''){
            $goodsList->where('name','like','%'.trim($keyword).'%')->orWhere('upc','like','%'.trim($keyword).'%');
        }

        if($status !== ''){
            $goodsList = $goodsList->whereStatus($status);
        }

        if($classifyId != 0){
            $goodsList = $goodsList->whereClassifyId($classifyId);
        }

        if($from != ''){
            $goodsList = $goodsList->whereFrom($from);
        }

        $pageInfo['total'] = $goodsList->count();

        $goodsList = $goodsList->orderByDesc('id')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($goodsList) > 0){
            foreach ($goodsList as $goods) {
                $goods->thumb_url = SystemMedicine::getSystemMedicineImg($goods->id);

                if($goods->status == 1){
                    $goods->status_name = '开启';
                }else{
                    $goods->status_name = '关闭';
                }

                if($goods->from == 'admin'){
                    $goods->from_name = '平台创建';
                }elseif($goods->from == 'enterprise'){
                    $goods->from_name = '商家创建';
                }else{
                    $goods->cfrom_name = '未知';
                }

                //商品链接
                $goods->link_url = '';

                if($goods->second_classify_id){
                    $firstClassifyName = Classify::getClassifyName($goods->first_classify_id);

                    $secondClassifyName = Classify::getClassifyName($goods->second_classify_id);

                    if($secondClassifyName){
                        $goods->classify_name = $firstClassifyName . ' - ' . $secondClassifyName;
                    }else{
                        $goods->classify_name = $firstClassifyName;

                    }
                }else{
                    $goods->classify_name = Classify::getClassifyName($goods->first_classify_id);
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsList,'page_info' => $pageInfo]);
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $goods = SystemMedicine::whereId($id)->first();
        if($goods) {
            $goods->thumb_url = SystemMedicine::getSystemMedicineImgList($goods->id);

            $goods->classify_name = Classify::getClassifyName($goods->first_classify_id);

            if($goods->second_classify_id)
                $goods->chind_classify_name = Classify::getClassifyName($goods->second_classify_id);

            $goods->thumb_url = SystemMedicine::getSystemMedicineImgList($goods->id);

            $skuArr = [];
            $systemMedicineSkuList = SystemMedicineSku::whereSystemMedicineId($goods->id)->get();
            if(count($systemMedicineSkuList) > 0){
                foreach ($systemMedicineSkuList as $systemMedicineSku) {
                    $sku = Sku::whereId($systemMedicineSku->sku_id)->first();
                    if($sku){
                        array_push($skuArr,$sku);
                    }
                }
            }

            $goods->sku_list = $skuArr;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goods]);
    }

    /**
     * 编辑商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGoods(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $upc                                 = $request->get('upc') ?? '';
        $name                                = $request->get('name') ?? '';
        $classifyId                          = $request->get('classify_id') ?? 0;
        $firstClassifyId                     = $request->get('first_classify_id') ?? 0;
        $secondClassifyId                    = $request->get('second_classify_id') ?? 0;
        $approvalNumber                      = $request->get('approval_number') ?? '';
        $specification                       = $request->get('specification') ?? '';
        $thumbId                             = $request->get('thumb_id') ?? 0;
        $manufacturer                        = $request->get('manufacturer') ?? '';
        $manufacturerAddress                 = $request->get('manufacturer_address') ?? '';
        $manufacturerContact                 = $request->get('manufacturer_contact') ?? '';
        $electronicRegulatoryCode            = $request->get('electronic_regulatory_code') ?? '';
        $usageAndDosage                      = $request->get('usage_and_dosage') ?? '';
        $indications                         = $request->get('indications') ?? '';
        $adaptToTheCrowd                     = $request->get('adapt_to_the_crowd') ?? '';
        $component                           = $request->get('component') ?? '';
        $adverseReactions                    = $request->get('adverse_reactions') ?? '';
        $contraindications                   = $request->get('contraindications') ?? '';
        $precautions                         = $request->get('precautions') ?? '';
        $interaction                         = $request->get('interaction') ?? '';
        $medicationForChildren               = $request->get('medication_for_children') ?? '';
        $medicationForPregnancyXLactation    = $request->get('medication_for_pregnancy_x_lactation') ?? '';
        $medicationForAged                   = $request->get('medication_for_aged') ?? '';
        $properties                          = $request->get('properties') ?? '';
        $packing                             = $request->get('packing') ?? '';
        $dosageForm                          = $request->get('dosage_form') ?? '';
        $storage                             = $request->get('storage') ?? '';
        $pharmacologicalAction               = $request->get('pharmacological_action') ?? '';
        $expiryDate                          = $request->get('expiry_date') ?? '';
        $detail                              = $request->get('detail') ?? '';
        $status                              = $request->get('status') ?? 0;
        $skuArr                              = $request->get('sku_arr');
        $id                                  = $request->get('id') ?? 0;

        $upcExists = SystemMedicine::whereUpc($upc)->first();

        $merchantMedicine = SystemMedicine::whereId($id)->first();

        if($upcExists && ($merchantMedicine && $upcExists->id != $merchantMedicine->id))
            return response()->json(['level' => 'error','message' => 'upc码已存在']);

        if(!$merchantMedicine){
            if($upcExists)
                return response()->json(['level' => 'error','message' => 'upc码已存在']);

            $merchantMedicine = new SystemMedicine();
            $merchantMedicine->from = 'admin';
        }

        $merchantMedicine->upc                                   = $upc;
        $merchantMedicine->name                                  = $name;
        $merchantMedicine->drug_type                             = $classifyId;
        $merchantMedicine->first_classify_id                     = $firstClassifyId;
        $merchantMedicine->second_classify_id                    = $secondClassifyId;
        $merchantMedicine->approval_number                       = $approvalNumber;
        $merchantMedicine->specification                         = $specification;
        $merchantMedicine->manufacturer                          = $manufacturer;
        $merchantMedicine->manufacturer_address                  = $manufacturerAddress;
        $merchantMedicine->manufacturer_contact                  = $manufacturerContact;
        $merchantMedicine->electronic_regulatory_code            = $electronicRegulatoryCode;
        $merchantMedicine->usage_and_dosage                      = $usageAndDosage;
        $merchantMedicine->indications                           = $indications;
        $merchantMedicine->adapt_to_the_crowd                    = $adaptToTheCrowd;
        $merchantMedicine->component                             = $component;
        $merchantMedicine->adverse_reactions                     = $adverseReactions;
        $merchantMedicine->contraindications                     = $contraindications;
        $merchantMedicine->precautions                           = $precautions;
        $merchantMedicine->interaction                           = $interaction;
        $merchantMedicine->medication_for_children               = $medicationForChildren;
        $merchantMedicine->medication_for_pregnancy_x_lactation  = $medicationForPregnancyXLactation;
        $merchantMedicine->medication_for_aged                   = $medicationForAged;
        $merchantMedicine->properties                            = $properties;
        $merchantMedicine->packing                               = $packing;
        $merchantMedicine->dosage_form                           = $dosageForm;
        $merchantMedicine->storage                               = $storage;
        $merchantMedicine->pharmacological_action                = $pharmacologicalAction;
        $merchantMedicine->expiry_date                           = $expiryDate;
        $merchantMedicine->detail                                = $detail;
        $merchantMedicine->status                                = $status;
        $merchantMedicine->save();

        if(is_array($skuArr)){
            $systemMedicineSkuList = SystemMedicineSku::whereSystemMedicineId($merchantMedicine->id)->get();
            if(count($systemMedicineSkuList) > 0){
                foreach ($systemMedicineSkuList as $systemMedicineSku) {
                    $systemMedicineSku->delete();
                }
            }

            if(count($skuArr) > 0){
                foreach ($skuArr as $sku) {
                    $newSystemMedicineSku = new SystemMedicineSku();
                    $newSystemMedicineSku->system_medicine_id        = $merchantMedicine->id;
                    $newSystemMedicineSku->sku_id                    = $sku;
                    $newSystemMedicineSku->save();
                }
            }
        }

        if(is_array($thumbId)){
            $merchantMedicineImgList = SystemMedicineImg::whereSystemMedicineId($merchantMedicine->id)->get();
            if(count($merchantMedicineImgList) > 0){
                foreach ($merchantMedicineImgList as $merchantMedicineImg) {
                    $merchantMedicineImg->delete();
                }
            }

            if(count($thumbId) > 0){
                foreach ($thumbId as $img) {
                    $newMerchantMedicineImg = new SystemMedicineImg();
                    $newMerchantMedicineImg->system_medicine_id = $merchantMedicine->id;
                    $newMerchantMedicineImg->img_id               = $img;
                    $newMerchantMedicineImg->save();
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $merchantMedicine]);
    }

    /**
     * 改变商品状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeGoodsShop(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = AdminManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $systemMedicine = SystemMedicine::whereId($id)->first();
        if(!$systemMedicine)
            return response()->json(['level' => 'error','message' => '该药品不存在']);

        if($systemMedicine->status == 1){
            $systemMedicine->status = 0;
        }else{
            $systemMedicine->status = 1;
        }

        $systemMedicine->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $systemMedicine]);
    }

    /**
     * 删除商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delGoods(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $merchantMedicine = SystemMedicine::whereId($id)->first();
        if(!$merchantMedicine)
            return response()->json(['level' => 'error','message' => '该药品不存在']);

        $merchantMedicine->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $merchantMedicine]);
    }

    /**
     * 商品审核列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsApplyList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page         = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit        = !is_null($request->get('limit')) ? $request->get('limit') : 16;
        $enterpriseId = $request->get('enterprise_id') ?? 0;
        $review       = $request->get('review');

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var MerchantMedicineApply $goods */
        $goodsApplyList = MerchantMedicineApply::whereNull('deleted_at');

        if($enterpriseId != 0){
            $goodsApplyList->whereEnterpriseId($enterpriseId);
        }

        if(is_numeric($review)){
            $goodsApplyList = $goodsApplyList->whereReview($review);
        }

        $pageInfo['total'] = $goodsApplyList->count();

        $goodsApplyList = $goodsApplyList->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($goodsApplyList) > 0){
            foreach ($goodsApplyList as $goods) {
                $imgUrl = '';
                if($goods->thumb_id){
                    $goodsImgList = json_decode($goods->thumb_id,true);
                    if(count($goodsImgList) > 0){
                        $imgUrl = FileManager::getImgUrl($goodsImgList[0]);
                    }
                }
                $goods->thumb_url = $imgUrl;

                $goods->enterprise_name = Enterprise::getEnterpriseName($goods->enterprise_id);

                $goods->merchant_name = Merchant::getMerchantName($goods->merchant_id);

                if($goods->review == 1){
                    $goods->review_name = '通过';
                }elseif($goods->review == 2){
                    $goods->review_name = '拒绝';
                }else{
                    $goods->review_name = '待审核';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsApplyList,'page_info' => $pageInfo]);
    }

    /**
     * 商品审核详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsApplyDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $goodsApply = MerchantMedicineApply::whereId($id)->first();
        if($goodsApply){
            $goodsImgArr = [];
            if($goodsApply->thumb_id){
                $goodsImgList = json_decode($goodsApply->thumb_id,true);
                $goodsApply->thumb_id = $goodsImgList;
                if(count($goodsImgList) > 0){
                    foreach ($goodsImgList as $goodsImg) {
                        $imgUrl = FileManager::getImgUrl($goodsImg);
                        array_push($goodsImgArr,$imgUrl);
                    }
                }
            }
            $goodsApply->thumb_url = $goodsImgArr;

            $goodsApply->enterprise_name = Enterprise::getEnterpriseName($goodsApply->enterprise_id);

            $goodsApply->merchant_name = Merchant::getDeliveryName($goodsApply->merchant_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsApply]);
    }

    /**
     * 编辑商品审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGoodsApply(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id',0);
        $upc                                 = $request->get('upc') ?? '';
        $name                                = $request->get('name') ?? '';
        $typeId                              = $request->get('type_id') ?? 0;
        $skuSsn                              = $request->get('sku_ssn') ?? '';
        $approvalNumber                      = $request->get('approval_number') ?? '';
        $specification                       = $request->get('specification') ?? '';
        $thumbId                             = $request->get('thumb_id') ?? 0;
        $sellingPrice                        = $request->get('selling_price') ?? 0;
        $stock                               = $request->get('stock') ?? 0;
        $manufacturer                        = $request->get('manufacturer') ?? '';
        $manufacturerAddress                 = $request->get('manufacturer_address') ?? '';
        $manufacturerContact                 = $request->get('manufacturer_contact') ?? '';
        $electronicRegulatoryCode            = $request->get('electronic_regulatory_code') ?? '';
        $usageAndDosage                      = $request->get('usage_and_dosage') ?? '';
        $indications                         = $request->get('indications') ?? '';
        $adaptToTheCrowd                     = $request->get('adapt_to_the_crowd') ?? '';
        $component                           = $request->get('component') ?? '';
        $adverseReactions                    = $request->get('adverse_reactions') ?? '';
        $contraindications                   = $request->get('contraindications') ?? '';
        $precautions                         = $request->get('precautions') ?? '';
        $interaction                         = $request->get('interaction') ?? '';
        $medicationForChildren               = $request->get('medication_for_children') ?? '';
        $medicationForPregnancyXLactation    = $request->get('medication_for_pregnancy_x_lactation') ?? '';
        $medicationForAged                   = $request->get('medication_for_aged') ?? '';
        $properties                          = $request->get('properties') ?? '';
        $packing                             = $request->get('packing') ?? '';
        $dosageForm                          = $request->get('dosage_form') ?? '';
        $storage                             = $request->get('storage') ?? '';
        $pharmacologicalAction               = $request->get('pharmacological_action') ?? '';
        $expiryDate                          = $request->get('expiry_date') ?? '';
        $detail                              = $request->get('detail') ?? '';

        $systemMedicine = SystemMedicine::whereUpc($upc)->first();
        if($systemMedicine)
            return response()->json(['level' => 'error','message' => '该商品已录入商品库']);

        $merchantMedicineApply = MerchantMedicineApply::whereId($id)->first();
        if(!$merchantMedicineApply)
            return response()->json(['level' => 'error','message' => '该审核不存在']);

        $merchantMedicineApplyIsExists = MerchantMedicineApply::whereUpc($upc)->whereReview(0)->where('id','<>',$merchantMedicineApply->id)->first();
        if($merchantMedicineApplyIsExists)
            return response()->json(['level' => 'error','message' => '该商品正在审核中']);

        $merchantMedicineApply->upc                                   = $upc;
        $merchantMedicineApply->name                                  = $name;
        $merchantMedicineApply->thumb_id                              = json_encode($thumbId);
        $merchantMedicineApply->drug_type                             = $typeId;
        $merchantMedicineApply->sku_ssn                               = $skuSsn;
        $merchantMedicineApply->approval_number                       = $approvalNumber;
        $merchantMedicineApply->specification                         = $specification;
        $merchantMedicineApply->selling_price                         = $sellingPrice;
        $merchantMedicineApply->stock                                 = $stock;
        $merchantMedicineApply->manufacturer                          = $manufacturer;
        $merchantMedicineApply->manufacturer_address                  = $manufacturerAddress;
        $merchantMedicineApply->manufacturer_contact                  = $manufacturerContact;
        $merchantMedicineApply->electronic_regulatory_code            = $electronicRegulatoryCode;
        $merchantMedicineApply->usage_and_dosage                      = $usageAndDosage;
        $merchantMedicineApply->indications                           = $indications;
        $merchantMedicineApply->adapt_to_the_crowd                    = $adaptToTheCrowd;
        $merchantMedicineApply->component                             = $component;
        $merchantMedicineApply->adverse_reactions                     = $adverseReactions;
        $merchantMedicineApply->contraindications                     = $contraindications;
        $merchantMedicineApply->precautions                           = $precautions;
        $merchantMedicineApply->interaction                           = $interaction;
        $merchantMedicineApply->medication_for_children               = $medicationForChildren;
        $merchantMedicineApply->medication_for_pregnancy_x_lactation  = $medicationForPregnancyXLactation;
        $merchantMedicineApply->medication_for_aged                   = $medicationForAged;
        $merchantMedicineApply->properties                            = $properties;
        $merchantMedicineApply->packing                               = $packing;
        $merchantMedicineApply->dosage_form                           = $dosageForm;
        $merchantMedicineApply->storage                               = $storage;
        $merchantMedicineApply->pharmacological_action                = $pharmacologicalAction;
        $merchantMedicineApply->expiry_date                           = $expiryDate;
        $merchantMedicineApply->detail                                = $detail;
        $merchantMedicineApply->save();

        return response()->json(['level' => 'success','message' => '修改成功','data' => $merchantMedicineApply]);
    }

    /**
     * 审核商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function goodsReview(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id   = $request->get('id') ?? 0;
        $type = $request->get('type') ?? 'refuse';

        $merchantMedicineApply = MerchantMedicineApply::whereId($id)->first();
        if(!$merchantMedicineApply)
            return response()->json(['level' => 'error','message' => '商品审核不存在']);

        if($merchantMedicineApply->review == 1)
            return response()->json(['level' => 'error','message' => '审核已通过']);

        if($merchantMedicineApply->review == 2)
            return response()->json(['level' => 'error','message' => '审核已拒绝']);

        if($type == 'pass'){
            $systemMedicine = SystemMedicine::whereUpc($merchantMedicineApply->upc)->first();
            if($systemMedicine)
                return response()->json(['level' => 'error','message' => '该药品已存在']);

            $newSystemMedicine = new SystemMedicine();
            $newSystemMedicine->upc                                   = $merchantMedicineApply->upc;
            $newSystemMedicine->name                                  = $merchantMedicineApply->name;
//            $newSystemMedicine->thumb_id                              = $merchantMedicineApply->thumb_id;
            $newSystemMedicine->approval_number                       = $merchantMedicineApply->approval_number;
            $newSystemMedicine->specification                         = $merchantMedicineApply->specification;
            $newSystemMedicine->manufacturer                          = $merchantMedicineApply->manufacturer;
            $newSystemMedicine->manufacturer_address                  = $merchantMedicineApply->manufacturer_address;
            $newSystemMedicine->manufacturer_contact                  = $merchantMedicineApply->manufacturer_contact;
            $newSystemMedicine->electronic_regulatory_code            = $merchantMedicineApply->electronic_regulatory_code;
            $newSystemMedicine->usage_and_dosage                      = $merchantMedicineApply->usage_and_dosage;
            $newSystemMedicine->indications                           = $merchantMedicineApply->indications;
            $newSystemMedicine->adapt_to_the_crowd                    = $merchantMedicineApply->adapt_to_the_crowd;
            $newSystemMedicine->component                             = $merchantMedicineApply->component;
            $newSystemMedicine->adverse_reactions                     = $merchantMedicineApply->adverse_reactions;
            $newSystemMedicine->contraindications                     = $merchantMedicineApply->contraindications;
            $newSystemMedicine->precautions                           = $merchantMedicineApply->precautions;
            $newSystemMedicine->interaction                           = $merchantMedicineApply->interaction;
            $newSystemMedicine->medication_for_children               = $merchantMedicineApply->medication_for_children;
            $newSystemMedicine->medication_for_pregnancy_x_lactation  = $merchantMedicineApply->medication_for_pregnancy_x_lactation;
            $newSystemMedicine->medication_for_aged                   = $merchantMedicineApply->medication_for_aged;
            $newSystemMedicine->properties                            = $merchantMedicineApply->properties;
            $newSystemMedicine->packing                               = $merchantMedicineApply->packing;
            $newSystemMedicine->dosage_form                           = $merchantMedicineApply->dosage_form;
            $newSystemMedicine->storage                               = $merchantMedicineApply->storage;
            $newSystemMedicine->pharmacological_action                = $merchantMedicineApply->pharmacological_action;
            $newSystemMedicine->expiry_date                           = $merchantMedicineApply->expiry_date;
            $newSystemMedicine->detail                                = $merchantMedicineApply->detail;
            $newSystemMedicine->from                                  = 'enterprise';
            $newSystemMedicine->status                                = 1;
            $newSystemMedicine->save();

            $imgList = json_decode($merchantMedicineApply->thumb_id,true);
            if(count($imgList) > 0){
                foreach($imgList as $img) {
                    $newMerchantMedicineImg = new SystemMedicineImg();
                    $newMerchantMedicineImg->system_medicine_id   =  $newSystemMedicine->id;
                    $newMerchantMedicineImg->img_id               =  $img;
                    $newMerchantMedicineImg->save();
                }
            }

            $merchantMedicineApply->review = 1;
            $merchantMedicineApply->save();
        }elseif($type == 'refuse'){
            $merchantMedicineApply->review = 2;
            $merchantMedicineApply->save();
        }else{
            return response()->json(['level' => 'error','message' => '参数错误']);
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $merchantMedicineApply]);
    }

    /**
     * 商品分类列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsClassifyList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 16;
        $pid        = $request->get('pid') ?? 0;
        $keyword    = $request->get('keyword','');
        $status    = $request->get('status');

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        $goodsClassifyList = Classify::wherePid($pid)->whereType('medicine');

        if($keyword != ''){
            $goodsClassifyList->where('name','like','%'.trim($keyword).'%');
        }

        if(is_numeric($status)){
            $goodsClassifyList = $goodsClassifyList->whereStatus($status);
        }

        $pageInfo['total'] = $goodsClassifyList->count();

        $goodsClassifyList = $goodsClassifyList->orderBy('sort')->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($goodsClassifyList) > 0){
            foreach ($goodsClassifyList as $goodsClassify) {
                $goodsClassify->img_url = FileManager::getImgUrl($goodsClassify->img_id);

                if($goodsClassify->status == 1){
                    $goodsClassify->status_name = '开启';
                }else{
                    $goodsClassify->status_name = '关闭';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsClassifyList,'page_info' => $pageInfo]);
    }

    /**
     * 商品分类详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsClassifyDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $goodsClassify = Classify::whereId($id)->first();
        if($goodsClassify){
            $goodsClassify->img_url = FileManager::getImgUrl($goodsClassify->img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $goodsClassify]);
    }

    /**
     * 编辑商品分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGoodsClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name       = $request->get('name') ?? '';
        $desc       = $request->get('desc') ?? '';
        $pid        = $request->get('pid') ?? 0;
        $imgId      = $request->get('img_id') ?? 0;
        $sort       = $request->get('sort') ?? 0;
        $status     = $request->get('status') ?? 0;
        $linkUrl    = $request->get('link_url') ?? '';
        $id         = $request->get('id') ?? 0;

        $goodsClassify = Classify::whereId($id)->first();
        if(!$goodsClassify)
            $goodsClassify = new Classify();

        $goodsClassify->pid           = $pid;
        $goodsClassify->name          = $name;
        $goodsClassify->desc          = $desc;
        $goodsClassify->type          = 'medicine';
        $goodsClassify->link_url      = $linkUrl;
        $goodsClassify->img_id        = $imgId;
        $goodsClassify->sort          = $sort;
        $goodsClassify->status        = $status;
        $goodsClassify->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $goodsClassify]);
    }

    /**
     * 删除商品分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delGoodsClassify(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $goodsClassify = Classify::whereId($id)->first();
        if(!$goodsClassify)
            return response()->json(['level' => 'error','message' => '分类不存在']);

        $goodsClassify->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $goodsClassify]);
    }

    /**
     * 规格列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSkuList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page           = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $skuList = Sku::whereNull('deleted_at');

        $pageInfo['total'] = $skuList->count();

        $skuList = $skuList->orderBy('sort')->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $skuList,'page_info' => $pageInfo]);
    }

    /**
     * 规格详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSkuDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $sku = Sku::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $sku]);
    }

    /**
     * 设置规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setSku(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id   = $request->get('id') ?? 0;
        $name = $request->get('name') ?? '';
        $sort = $request->get('sort') ?? '';

        $sku = Sku::whereId($id)->first();
        if(!$sku)
            $sku = new Sku();

        $sku->name       = $name;
        $sku->sort       = $sort;
        $sku->status     = 1;
        $sku->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $sku]);
    }

    /**
     * 删除规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delSku(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id   = $request->get('id') ?? 0;

        $sku = Sku::whereId($id)->first();
        if(!$sku)
            return response()->json(['level' => 'error','message' => '规格不存在']);

        $sku->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $sku]);
    }

    /**
     * 规格属性列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function skuValueList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page           = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $skuId          = $request->get('sku_id') ?? 0;

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $skuValueList = SkuValue::whereSkuId($skuId);

        $pageInfo['total'] = $skuValueList->count();

        $skuValueList = $skuValueList->orderBy('sort')->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($skuValueList) > 0){
            foreach ($skuValueList as $skuValue) {
                $skuValue->sku_name = Sku::getSkuName($skuValue->sku_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $skuValueList,'page_info' => $pageInfo]);
    }

    /**
     * 规格属性详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function skuValueDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $skuValue = SkuValue::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $skuValue]);
    }

    /**
     * 设置规格属性
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setSkuValue(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id     = $request->get('id') ?? 0;
        $skuId  = $request->get('sku_id') ?? 0;
        $value  = $request->get('value') ?? '';
        $sort   = $request->get('sort') ?? '';

        $skuValue = SkuValue::whereId($id)->first();
        if(!$skuValue)
            $skuValue = new SkuValue();

        $skuValue->value     = $value;
        $skuValue->sku_id    = $skuId;
        $skuValue->sort      = $sort;
        $skuValue->status    = 1;
        $skuValue->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $skuValue]);
    }

    /**
     * 删除规格属性
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delSkuValue(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id     = $request->get('id') ?? 0;

        $skuValue = SkuValue::whereId($id)->first();
        if(!$skuValue)
            return response()->json(['level' => 'error','message' => '商品属性不存在']);

        $skuValue->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $skuValue]);
    }

    public static function enterGoods(){
        echo 'starting import'.PHP_EOL;
        ini_set('memory_limit','1024M');
        echo 'set memory_limit=700M'.PHP_EOL;
        echo 'starting load excel'.PHP_EOL;
        $GoodsList = Excel::selectSheetsByIndex(0)
            ->load(storage_path() . '/app/' . 'import/tb_drugs.xlsx','UTF-8')
            ->toArray();
        echo 'load excel finish'.PHP_EOL;
        if(count($GoodsList) > 0){
            foreach ($GoodsList as $key => $goods) {
                $drugId                 = $goods['drug_id'];
                $upc                    = $goods['bar_code'];
                $name                   = $goods['drug_name'];
                $simpleCode             = $goods['simple_code'];
                $specification          = $goods['specifications'];
                $dosageForm             = $goods['dosage_form'];
                $packing                = $goods['packing_unit'];
                $approvalNumber         = $goods['approval_number'];
                $classifyId             = $goods['drug_type'];
                $natureClass            = $goods['nature_class'];
                $useClass               = $goods['use_class'];
                $drugBrand              = $goods['drug_brand'];
                $component              = $goods['constituents'];
                $properties             = $goods['property'];
                $indications            = $goods['indication'];
                $usageAndDosage         = $goods['dosage'];
                $adverseReactions       = $goods['adverse_reactions'];
                $contraindications      = $goods['contraindication'];
                $precautions            = $goods['attentions'];
                $interaction            = $goods['interreaction'];
                $storage                = $goods['depot'];
                $manufacturer           = $goods['manufacturer'];
                $manufacturerAddress    = $goods['address'];
                $bitCode                = $goods['bit_code'];
                $picture                = $goods['picture'];
                if ($useClass){
                    $classify=Classify::firstOrCreate(['name'=>$useClass],[
                        'type'=>'medicine',
                        'desc'=>'药品库导入生成的分类',
                        'status'=>1
                    ]);
                } else {
                    $classify=false;
                }

                $newGoods = new SystemMedicine();
                $newGoods->disease              = $drugId ? $drugId : '';
                $newGoods->upc                  = $upc;
                $newGoods->name                 = $name ? $name : '';
                $newGoods->simple_code          = $simpleCode ? $simpleCode : '';
                $newGoods->specification        = $specification ? $specification : '';
                $newGoods->dosage_form          = $dosageForm ? $dosageForm : '';
                $newGoods->packing              = $packing ? $packing : "";
                $newGoods->approval_number      = $approvalNumber ? $approvalNumber : '';
                $newGoods->classify_id          = $classify ? $classify->id : '';
                $newGoods->drug_type            = $classifyId;
                $newGoods->nature_class         = $natureClass ? $natureClass : '';
                $newGoods->use_class            = $useClass ? $useClass : '';
                $newGoods->drug_brand           = $drugBrand ? $drugBrand : '';
                $newGoods->component            = $component ? $component : '';
                $newGoods->properties           = $properties ? $properties : '';
                $newGoods->indications          = $indications ? $indications : '';
                $newGoods->usage_and_dosage     = $usageAndDosage ? $usageAndDosage : '';
                $newGoods->adverse_reactions    = $adverseReactions ? $adverseReactions : '';
                $newGoods->contraindications    = $contraindications ? $contraindications : '';
                $newGoods->precautions          = $precautions ? $precautions : '';
                $newGoods->interaction          = $interaction ? $interaction : '' ;
                $newGoods->storage              = $storage ? $storage : '';
                $newGoods->manufacturer         = $manufacturer ? $manufacturer : '';
                $newGoods->manufacturer_address = $manufacturerAddress ? $manufacturerAddress : '';
                $newGoods->bit_code             = $bitCode ? $bitCode : '';
                $newGoods->save();


                $picture = str_replace('/upload/picture/','',$picture);

                $imgName = str_replace('.jpg','',$picture);

                $toDirPath = 'web/systemmidicineimg';

                $files = Files::whereFileMd5($imgName)->first();
                if(!$files){
                    $files = new Files();
                    $files->file_name = $imgName;
                    $files->file_url  = $toDirPath;
                    $files->file_type = ".jpg";
                    $files->file_ext  = 'image/jpeg';
                    $files->disk      = 'oss';
                    $files->save();
                }

                $imageModel = Images::whereFileId($files->id)->first();
                if (!$imageModel) {
                    $imageModel = new Images();
                    $imageModel->file_id = $files->id;
                    $imageModel->img_name = $imgName;
                    $imageModel->img_type = $files->file_type;
                    $imageModel->save();
                }

                $newGoodsImg = new SystemMedicineImg();
                $newGoodsImg->system_medicine_id = $newGoods->id;
                $newGoodsImg->img_id             = $imageModel->id;
                $newGoodsImg->save();
                if ($key%100==0){
                    echo 'finish:'.$key.'records'.PHP_EOL;
                }

            }
        }

        return 'finish';
    }

    public static function change(){
        echo 'starting change'.PHP_EOL;
        ini_set('memory_limit','128M');
        echo 'set memory_limit=128M'.PHP_EOL;
        echo 'starting load data'.PHP_EOL;
//        for ($i=0;$i<=15;$i++){
//            $data=SystemMedicine::where('id','>',0);
//            $data=$data->offset($i*5000)
//                ->limit(5000)
//                ->get();
//
//        }
        $data=DB::select('select distinct use_class from system_medicine where deleted_at is null');
//        $xiID=DB::table('system_medicine')
//            ->where('nature_class','=','西药')
//            ->pluck('id')
//            ->toArray();
        //一级分类-中成药109
        //        西药110
        //处理中成药
        $i=1;
        $total=count($data);
        foreach ($data as $item){
            if ($item->use_class!='未分类'){
                $existZHONG=SystemMedicine::whereNatureClass('中成药')->whereUseClass($item->use_class)->first();
                if ($existZHONG){
                    $classify=Classify::firstOrCreate(['name'=>$item->use_class,'pid'=>109],['desc'=>'药品库二级分类','type'=>'medicine']);
                    SystemMedicine::whereNatureClass('中成药')->whereUseClass($item->use_class)
                        ->update(['second_classify_id'=>$classify->id]);
                }
                echo 'finish:'.'中成药-'.$item->use_class.'-........';

                $existXI=SystemMedicine::whereNatureClass('西药')->whereUseClass($item->use_class)->first();
                if ($existXI){
                    $classify=Classify::firstOrCreate(['name'=>$item->use_class,'pid'=>110],['desc'=>'药品库二级分类','type'=>'medicine']);
                    SystemMedicine::whereNatureClass('西药')->whereUseClass($item->use_class)
                        ->update(['second_classify_id'=>$classify->id]);
                }
                echo 'finish:'.'西药-'.$item->use_class.'-----'.$i.'/'.$total.PHP_EOL.PHP_EOL;

            }
            $i=$i+1;


        }
//        $item->use_class
//            var_dump($item->use_class);

        return 'success';

    }

    public function enterGoodsTwo(){

        $this->dispatchNow(new import());

        return response()->json(['level' => 'success','message' => '成功']);
    }
}
